//
//  ZYXPCAddViewController.m
//  OCDataStore
//
//  添加联系人页面
//

#import "ZYXPCAddViewController.h"
#import "ZYXContact.h"

@interface ZYXPCAddViewController ()

@property (weak, nonatomic) IBOutlet UITextField    *phoneField;
@property (weak, nonatomic) IBOutlet UITextField    *nameField;
@property (weak, nonatomic) IBOutlet UIButton       *addBtn;

- (IBAction)add;

@end

@implementation ZYXPCAddViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.phoneField];
    
    // 退出键盘
    //    [self.nameField resignFirstResponder];
    //    [self.view endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  文本框的文字发生改变的时候调用
 */
- (void)textChange
{
    self.addBtn.enabled = (self.nameField.text.length && self.phoneField.text.length);
}

/**
 *  控制器的view完全显示的时候调用
 */
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 让姓名文本框成为第一响应者(叫出键盘)
    [self.nameField becomeFirstResponder];
}

/**
 *  添加
 */
- (IBAction)add {
    // 1.关闭当前添加联系人控制器
    [self.navigationController popViewControllerAnimated:YES];
    
    // 2.传递所添加的联系人模型数据给上一个联系人列表控制器(ZYXPCContactsViewController)
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(addViewController:didAddContact:)]) {
        ZYXContact *contact = [[ZYXContact alloc] init];
        contact.name  = self.nameField.text;
        contact.phone = self.phoneField.text;
        [self.delegate addViewController:self didAddContact:contact];
    }
}

@end
